#include "graphics/submesh.h"
#include "graphics/scenemanager.h"

namespace dw
{
	namespace graphics
	{

		SubMesh::SubMesh()
		{
		}

		SubMesh::SubMesh(primitive::types primitiveType, const uint32 indexStart, const uint32 indexCount, const uint32 vertexIndexStart, const uint32 vertexIndexEnd, const std::string& materialName) :
			_primitiveType(primitiveType),
			_indexStart(indexStart),
			_indexCount(indexCount),
			_vertexIndexStart(vertexIndexStart),
			_vertexIndexEnd(vertexIndexEnd),
			_materialName(materialName)
		{
		}

		SubMesh::~SubMesh()
		{
		}

		std::ostream& operator<<(std::ostream& os, const SubMesh& subMesh)
		{	
			unsigned materialNameLength = static_cast< unsigned >(subMesh._materialName.size());

			os.write(reinterpret_cast< const char* >(&subMesh._primitiveType), sizeof (unsigned));
			os.write(reinterpret_cast< const char* >(&subMesh._indexStart), sizeof (unsigned));
			os.write(reinterpret_cast< const char* >(&subMesh._indexCount), sizeof (unsigned));
			os.write(reinterpret_cast< const char* >(&subMesh._vertexIndexStart), sizeof (unsigned));
			os.write(reinterpret_cast< const char* >(&subMesh._vertexIndexEnd), sizeof (unsigned));
			os.write(reinterpret_cast< const char* >(&materialNameLength), sizeof (unsigned));
			os.write(reinterpret_cast< const char* >(subMesh._materialName.c_str()), materialNameLength);
			return os;
		}

		std::istream& operator>>(std::istream& is, SubMesh& subMesh)
		{
			unsigned materialNameLength;
			char* materialName;
			
			is.read(reinterpret_cast< char* >(&subMesh._primitiveType), sizeof (unsigned));
			is.read(reinterpret_cast< char* >(&subMesh._indexStart), sizeof (unsigned));
			is.read(reinterpret_cast< char* >(&subMesh._indexCount), sizeof (unsigned));
			is.read(reinterpret_cast< char* >(&subMesh._vertexIndexStart), sizeof (unsigned));
			is.read(reinterpret_cast< char* >(&subMesh._vertexIndexEnd), sizeof (unsigned));
			is.read(reinterpret_cast< char* >(&materialNameLength), sizeof (unsigned));
			materialName = new char[materialNameLength + 1];
			is.read(materialName, materialNameLength);
			materialName[materialNameLength] = '\0';
			subMesh._materialName = materialName;
			delete [] materialName;
			return is;
		}

	} // namespace graphics
} // namespace dw
